<?php


namespace App\Http\Middleware;


use App\Http\Common\BaseController;
use App\Models\Role;
use App\Models\User;
use Closure;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;

class Auth extends BaseController
{
    /**
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|mixed
     */
    public function handle($request, Closure $next){
        //获取当前请求的方法名
        $currentRouteName = '/' . Route::current()->uri;

        //排除白名单
        if (in_array($currentRouteName, config('whitelist.routes'))){
            return $next($request);
        }

        //获取token
        $token = $request->header("Authorization");

        //获取登录后的信息
        $userInfo = json_decode(Redis::get($token));

        //管理员未登录
        if (!$userInfo && $request->input('type')){
            return $this->returnJson(BaseController::ADMIN_NOT_LOGGED_IN, '管理员未登录');
        }

        //用户未登录
        if (!$userInfo){
            return $this->returnJson(BaseController::NOT_LOGGED_IN, '用户未登录');
        }

        $request->userId = $userInfo->id;

        //获取所有路由
        $routeAll = $this->getRouteAll($request->userId);

        foreach ($routeAll as $value){
            //判断用户是否拥有权限
            if ($value['route_url'] == $currentRouteName && $value['status'] == 1) {
                return $next($request);
            }
        }

        //判断是否是管理员
        if (isset($userInfo->type) && $userInfo->type == 1){
            return $this->returnJson(BaseController::NO_PERMISSION, '当前管理员没有访问权限');
        }

        return $this->returnJson(BaseController::NO_PERMISSION, '当前用户没有访问权限');
    }
}
